import { Body, Controller, Get, Post, Res, Session } from '@nestjs/common';
import { Response } from 'express';
import { UtilityService } from '../../shared/services/utility.service';
import { UserService } from '../../shared/services/user.service';

@Controller('admin')
export class AuthController {
  constructor(
    private readonly utilityService: UtilityService,
    private readonly userService: UserService,
  ) {}

  @Get('login')
  async showLogin(@Res() res: Response) {
    res.render('auth/login', { layout: false });
  }

  @Get('captcha')
  getCaptcha(@Res() res: Response, @Session() session: any) {
    const captcha = this.utilityService.generateCaptcha({
      size: 4,
      ignoreChars: '0o1il',
    });
    session.captcha = captcha?.text; // 存储验证码文本到session
    res.type('svg'); // 设置响应类型为SVG
    res.send(captcha.data); // 返回SVG图片
  }

  @Post('login')
  async login(
    @Body() body: any,
    @Res() res: Response,
    @Session() session: any,
  ) {
    const { password, username, captcha } = body;

    // 验证码校验
    if (captcha?.toLowerCase() !== session.captcha?.toLowerCase()) {
      return res.render('auth/login', { layout: false, message: '验证码错误' });
    }

    // 查询用户
    const user = await this.userService.findOne({
      where: { username },
    });

    // 用户不存在
    if (!user) {
      return res.render('auth/login', {
        layout: false,
        message: '用户名或密码错误',
      });
    }

    // 密码校验
    const isPasswordValid = await this.utilityService.comparePassword(
      password,
      user.password,
    );

    if (isPasswordValid) {
      session.user = user; // 存储用户信息到session
      return res.redirect(`/dashboard`); // 登录成功，重定向到仪表盘
    } else {
      return res.render('auth/login', {
        layout: false,
        message: '用户名或密码错误',
      });
    }
  }
}
